import { useEffect, useMemo } from 'react';

import type { HomeStatistics } from '@/api/homeApi';
import { DeviceListStatus, DeviceListType, getEnumItem } from '@/constants';
import { useECharts } from '@/hooks/useEcharts';
/**
 * 设备类型数据接口
 */
interface DeviceTypeData {
  /** 设备类型名称 */
  name: string;
  /** 设备数量 */
  value: number;
  /** 显示颜色 */
  color?: string;
}

// 设备状态项缓存，避免重复查找
const activeItemCache = new Map<string, DeviceTypeData>();

/**
 * 设备视图组件
 * 展示设备分布统计（环形图）和设备状态统计（多层环形图）
 */
const DeviceView: React.FC<{ data: HomeStatistics }> = ({ data }) => {
  // 图表实例钩子
  const { domRef, setOptions } = useECharts();
  const { domRef: domRef2, setOptions: setOptions2 } = useECharts();

  /**
   * 设备类型分布数据
   * 将API返回的设备类型统计数据转换为图表所需格式
   */
  const deviceData: DeviceTypeData[] = useMemo(() => {
    if (!data?.deviceTypeCount || !Array.isArray(data.deviceTypeCount)) {
      return [];
    }

    return data.deviceTypeCount
      .map(item => {
        if (!item.deviceType) return null;

        const enumItem = getEnumItem(DeviceListType, item.deviceType as string);
        return {
          name: enumItem?.label || '未知类型',
          value: Number(item.deviceCount || 0),
          color: enumItem?.color || '#cccccc',
        };
      })
      .filter((item): item is DeviceTypeData => item !== null);
  }, [data.deviceTypeCount]);

  /**
   * 设备状态分布数据
   * 将API返回的设备状态统计数据转换为图表所需格式
   */
  const deviceStatusData: DeviceTypeData[] = useMemo(() => {
    if (!data?.deviceStatusCount || !Array.isArray(data.deviceStatusCount)) {
      return [];
    }

    return data.deviceStatusCount
      .map(item => {
        if (!item.deviceStatus) return null;

        const enumItem = getEnumItem(DeviceListStatus, item.deviceStatus as string);
        return {
          name: enumItem?.label || '未知状态',
          value: Number(item.deviceCount || 0),
          color: enumItem?.color || '#cccccc',
        };
      })
      .filter((item): item is DeviceTypeData => item !== null);
  }, [data.deviceStatusCount]);

  /**
   * 根据设备状态名称获取对应的数据项（带缓存）
   * @param name 设备状态名称
   * @returns 设备状态数据项
   */
  const getDeviceStatusItemByName = (name: string): DeviceTypeData | undefined => {
    // 先从缓存中查找
    if (activeItemCache.has(name)) {
      return activeItemCache.get(name);
    }

    // 从数据中查找
    const item = deviceStatusData.find(i => i.name === name);
    if (item) {
      activeItemCache.set(name, item);
    }
    return item;
  };

  /**
   * 设备类型总数
   */
  const totalDevices = useMemo(() => {
    return deviceData.reduce((sum, item) => sum + item.value, 0);
  }, [deviceData]);

  /**
   * 设备状态总数
   */
  const totalStatusDevices = useMemo(() => {
    return deviceStatusData.reduce((sum, item) => sum + item.value, 0);
  }, [deviceStatusData]);

  // 配置图表
  useEffect(() => {
    setOptions({
      title: {
        text: `{number|${totalDevices}}\n{label|设备总数}`,
        left: 'center',
        top: 'center',
        textStyle: {
          align: 'center',
          verticalAlign: 'middle',
          rich: {
            number: {
              fontSize: 32,
              fontWeight: 'bold',
              color: '#1D2129',
              lineHeight: 48,
              align: 'center',
            },
            label: {
              fontSize: 14,
              fontWeight: 'normal',
              color: '#86909C',
              lineHeight: 20,
              align: 'center',
            },
          },
        },
      },
      grid: {
        left: '10%',
        top: '10%',
        right: '10%',
        bottom: '10%',
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)',
      },
      legend: {
        show: true,
        orient: 'vertical',
        right: '0%',
        top: '25%',
        itemWidth: 14,
        itemHeight: 14,
        itemGap: 16,
        textStyle: {
          color: '#5A6170',
          fontSize: 14,
          fontWeight: 'normal',
        },
        formatter: function (name: string) {
          const item = deviceData.find(d => d.name === name);
          return `${name}: ${item?.value || 0}个`;
        },
      },
      series: [
        {
          name: '设备分布',
          type: 'pie',
          radius: ['50%', '80%'], // 内外半径，形成环形
          center: ['50%', '50%'],
          avoidLabelOverlap: true,
          itemStyle: {
            borderRadius: 8,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: true,
            formatter: '{b}: {c}个', // 显示名称和数值
            position: 'outside',
            fontSize: 12,
            fontWeight: 'bold',
            color: '#5A6170',
            distanceToLabelLine: 5,
            lineHeight: 16,
            overflow: 'truncate', // 超出省略
            ellipsis: '...', // 省略符号
          },
          emphasis: {
            label: {
              show: true,
              formatter: '{b}: {c}个', // 显示名称和数值
              fontSize: 16,
              fontWeight: 'bold',
              color: '#5A6170',
            },
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
          },
          labelLine: {
            show: true,
            length: 15,
            length2: 10,
            smooth: true,
            lineStyle: {
              width: 1,
              type: 'solid',
            },
          },
          labelLayout: {
            hideOverlap: false,
            moveOverlap: 'shiftX',
          },
          data: deviceData.map(item => ({
            value: item.value,
            name: item.name,
            itemStyle: {
              color: item.color,
            },
          })),
        },
      ],
    });
  }, [setOptions, deviceData, totalDevices]);

  // 配置第二个图表 - 设备状态统计
  useEffect(() => {
    setOptions2({
      tooltip: {
        trigger: 'item',
        formatter: function (params: any) {
          // 只有当name不为空时才显示tooltip
          if (params.name) {
            return `${params.seriesName} <br/>${params.name}: ${params.value}个 (${params.percent}%)`;
          }
          return '';
        },
        show: true,
        // backgroundColor: 'rgba(255,255,255,0.95)',
        textStyle: {
          color: '#1D2129',
          fontSize: 14,
        },
      },
      legend: {
        show: true,
        orient: 'vertical',
        right: '5%',
        top: 'center',
        itemWidth: 4,
        itemHeight: 20,
        itemGap: 20,
        icon: 'roundRect',
        data: [
          {
            name: '待激活',
            icon: 'roundRect',
            itemStyle: {
              color: getDeviceStatusItemByName('待激活')?.color || '#4A90E2',
            },
          },
          {
            name: '离线',
            icon: 'roundRect',
            itemStyle: {
              color: getDeviceStatusItemByName('离线')?.color || '#FF8C42',
            },
          },
          {
            name: '在线',
            icon: 'roundRect',
            itemStyle: {
              color: getDeviceStatusItemByName('在线')?.color || '#50C878',
            },
          },
        ],
        textStyle: {
          rich: {
            online: {
              backgroundColor: `${getDeviceStatusItemByName('在线')?.color || '#50C878'}20`,
              padding: [8, 12, 8, 8],
              borderRadius: 6,
              color: '#5A6170',
              fontSize: 14,
            },
            offline: {
              backgroundColor: `${getDeviceStatusItemByName('离线')?.color || '#FF8C42'}20`,
              padding: [8, 12, 8, 8],
              borderRadius: 6,
              color: '#5A6170',
              fontSize: 14,
            },
            pending: {
              backgroundColor: `${getDeviceStatusItemByName('待激活')?.color || '#4A90E2'}20`,
              padding: [8, 12, 8, 8],
              borderRadius: 6,
              color: '#5A6170',
              fontSize: 14,
            },
          },
        },
        formatter: function (name: string) {
          const item = deviceStatusData.find(d => d.name === name);
          let styleKey = 'pending';
          if (name === '离线') styleKey = 'offline';
          if (name === '在线') styleKey = 'online';

          return `{${styleKey}|${name}    ${item?.value || 0}个}`;
        },
      },
      series: [
        // 在线设备环
        {
          name: '在线',
          z: 5,
          type: 'pie',
          radius: ['25%', '40%'],
          center: ['35%', '50%'],
          startAngle: 90,
          silent: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: 'transparent',
            borderWidth: 0,
          },
          label: {
            show: true,
            position: 'inside',
            formatter: function (params: any) {
              // 只在有名称的数据上显示名称和百分比
              if (params.name) {
                return `{name|${params.name}}\n{percent|${params.percent}%}`;
              }
              return '';
            },
            rich: {
              name: {
                color: '#5A6170',
                fontSize: 12,
                fontWeight: 'bold',
                lineHeight: 16,
              },
              percent: {
                color: '#5A6170',
                fontSize: 12,
                fontWeight: 'bold',
              },
            },
          },
          labelLine: {
            show: false,
          },
          emphasis: {
            disabled: true, // 禁用悬停放大效果
          },
          data: [
            {
              value: getDeviceStatusItemByName('在线')?.value || 0,
              name: '在线',
              itemStyle: { color: getDeviceStatusItemByName('在线')?.color || '#50C878' },
            },
            {
              value: totalStatusDevices - (getDeviceStatusItemByName('在线')?.value || 0),
              name: '',
              itemStyle: { color: '#F7F8FA' },
              // 背景部分，通过name为空字符来区分
            },
          ],
        },
        // 离线设备环
        {
          name: '离线',
          z: 4,
          type: 'pie',
          radius: ['50%', '65%'],
          center: ['35%', '50%'],
          startAngle: 90,
          silent: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: 'transparent',
            borderWidth: 0,
          },
          label: {
            show: true,
            position: 'inside',
            formatter: function (params: any) {
              // 只在有名称的数据上显示名称和百分比
              if (params.name) {
                return `{name|${params.name}}\n{percent|${params.percent}%}`;
              }
              return '';
            },
            rich: {
              name: {
                color: '#5A6170',
                fontSize: 12,
                fontWeight: 'bold',
                lineHeight: 16,
              },
              percent: {
                color: '#5A6170',
                fontSize: 12,
                fontWeight: 'bold',
              },
            },
          },
          labelLine: {
            show: false,
          },
          emphasis: {
            disabled: true, // 禁用悬停放大效果
          },
          data: [
            {
              value: getDeviceStatusItemByName('离线')?.value || 0,
              name: '离线',
              itemStyle: { color: getDeviceStatusItemByName('离线')?.color || '#FF8C42' },
            },
            {
              value: totalStatusDevices - (getDeviceStatusItemByName('离线')?.value || 0),
              name: '',
              itemStyle: { color: '#F7F8FA' },
              // 背景部分，通过name为空字符来区分
            },
          ],
        },
        // 待激活设备环
        {
          z: 3,
          name: '待激活',
          type: 'pie',
          radius: ['75%', '90%'],
          center: ['35%', '50%'],
          startAngle: 90,
          silent: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: 'transparent',
            borderWidth: 0,
          },
          label: {
            show: true,
            position: 'inside',
            formatter: function (params: any) {
              // 只在有名称的数据上显示名称和百分比
              if (params.name) {
                return `{name|${params.name}}\n{percent|${params.percent}%}`;
              }
              return '';
            },
            rich: {
              name: {
                color: '#5A6170',
                fontSize: 12,
                fontWeight: 'bold',
                lineHeight: 16,
              },
              percent: {
                color: '#5A6170',
                fontSize: 12,
                fontWeight: 'bold',
              },
            },
          },
          labelLine: {
            show: false,
          },
          emphasis: {
            disabled: true, // 禁用悬停放大效果
          },
          data: [
            {
              value: getDeviceStatusItemByName('待激活')?.value || 0,
              name: '待激活',
              itemStyle: { color: getDeviceStatusItemByName('待激活')?.color || '#4A90E2' },
            },
            {
              value: totalStatusDevices - (getDeviceStatusItemByName('待激活')?.value || 0),
              name: '',
              itemStyle: { color: '#F7F8FA' },
              // 背景部分，通过name为空字符来区分
            },
          ],
        },
      ],
    });
  }, [setOptions2, deviceStatusData, totalStatusDevices]);

  return (
    <div className="grid grid-cols-2 gap-6 my-4">
      <div className="public-card p-6 one">
        <div className="mb-2">
          <h3 className="text-lg font-semibold text-gray-800 mb-2">设备分布统计</h3>
        </div>
        <div ref={domRef} className="w-full h-80" style={{ minHeight: '220px' }} />
      </div>
      <div className="public-card p-6 two">
        <div className="mb-2">
          <h3 className="text-lg font-semibold text-gray-800 mb-2">设备状态统计</h3>
        </div>
        <div ref={domRef2} className="w-full h-80" style={{ minHeight: '220px' }} />
      </div>
    </div>
  );
};

export default DeviceView;
